﻿using System.Text;
using ZKTEcoPush.Models;

namespace ZKTEcoPush.Services
{
    public interface IPushService
    {
        // 下发登记人脸命令
        void AddCommand(CmdRecord cmd);

        // 获取待下发命令
        string GetCommands();

        // 收到人脸考勤事件
        event Action<List<AttendanceDataRecord>> DataRecordReceived;

        // 推送人脸考勤事件
        void PushDataRecords(List<AttendanceDataRecord> records);

    }
    public class PushService : IPushService
    {
        List<CmdRecord> CmdRecords = new List<CmdRecord>();
        object _lock = new object();

        public event Action<List<AttendanceDataRecord>> DataRecordReceived;

        public PushService()
        {

            Task.Run(async () =>
            {
                while (true)
                {
                    if (CmdRecords.Count < 5)
                    {
                        AddCommand(new CmdRecord()
                        {
                            CmdID = $"{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}",
                            CmdDesc = "ENROLL_BIO",  // 登记人脸，掌纹（一体化模板）
                            CmdContent = $"ENROLL_BIO TYPE={2}\tPIN={DateTime.Now.Second}\tCardNo={DateTime.Now.Second}\tRETRY={3}\tOVERWRITE={1}",
                        });
                    }

                    await Task.Delay(60_000);
                }
            });
        }

        public void AddCommand(CmdRecord cmd)
        {
            lock (_lock)
            {
                CmdRecords.Add(cmd);
            }
        }

        public string GetCommands()
        {
            StringBuilder sb = new StringBuilder();
            lock (_lock)
            {
                foreach (var cmd in CmdRecords)
                {
                    sb.AppendLine(cmd.ToString());
                }
                CmdRecords.Clear();
            }
            if (sb.Length == 0)
            {
                sb.Append("OK");
            }

            return sb.ToString();
        }

        public void PushDataRecords(List<AttendanceDataRecord> records)
        {
            DataRecordReceived?.Invoke(records);
        }
    }
}
